﻿using System.Web;
using System;
using System.IO;
using System.Diagnostics;

namespace Folks.Timer
{
    public class TimerModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new System.EventHandler(context_PreRequestHandlerExecute);
            context.PostRequestHandlerExecute += new System.EventHandler(context_PostRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, System.EventArgs e)
        {
            Stopwatch sw = Stopwatch.StartNew();
            HttpContext.Current.Items.Add("sw", sw);
        }

        void context_PostRequestHandlerExecute(object sender, System.EventArgs e)
        {
            Stopwatch sw = (Stopwatch)HttpContext.Current.Items["sw"];
            sw.Stop();

            string path = "C:\\Folks\\" + HttpContext.Current.Request.ApplicationPath + ".txt";
            FileStream stream = (!File.Exists(path))
                ? File.Create(path)
                : File.Open(path, FileMode.Append);

            StreamWriter writer = new StreamWriter(stream);
            writer.WriteLine((sw.ElapsedTicks * (1000.00 / Stopwatch.Frequency)));
            
            writer.Close();
        }

        #endregion
    }
}
